<?php
namespace app\shop\model;
use app\common\model\CommonModel;
use app\common\model\Category;
use app\common\model\Supplier;
use app\common\model\OrderGoods;
use app\common\model\Goods;
use app\common\model\Stock;
use think\Session;
use think\Db;

class GoodsModel extends CommonModel
{
	/**
	* 添加商品信息
	*/
	public static function setGoods($info)
	{
		$data['admin_id'] = Session::get('admin.admin_id');
		$data['shop_id'] = Session::get('admin.shop_id');
		$data['goods_name'] = $info['goods_name'];
		$data['abbreviation'] = $info['abbreviation'];
		$data['goods_sn'] = $info['goods_sn'];
		$data['category_id'] = $info['category_id'];
		$data['cat_id'] = $info['cat_id'];
		$data['brand_name'] = $info['brand_name'];
		$data['memory_name'] = $info['memory_name'];
		$data['attribute_name'] = $info['attribute_name'];
		$data['colour_name'] = $info['colour_name'];
		$data['marker'] = $info['marker'];
		$data['unit'] = $info['unit'];
		$data['selling_price'] = $info['selling_price'];
		$data['trade_price'] = $info['trade_price'];
		$data['profit_bonus'] = $info['profit_bonus'];
		$data['turnover_bonus'] = $info['turnover_bonus'];
		$data['bar_code'] = $info['bar_code'];
		$data['warning_number'] = $info['warning_number'];
		$data['warning_overdue'] = $info['warning_overdue'];
		$data['describes'] = $info['describes'];
		$data['addtime'] = time();
		if(!(new Goods())->setGoods($data))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 修改
	*/
	public static function editGoods($info)
	{
		$data['admin_id'] = Session::get('admin.admin_id');
		$data['shop_id'] = Session::get('admin.shop_id');
		$data['goods_name'] = $info['goods_name'];
		$data['abbreviation'] = $info['abbreviation'];
		$data['goods_sn'] = $info['goods_sn'];
		$data['category_id'] = $info['category_id'];
		$data['cat_id'] = $info['cat_id'];
		$data['brand_name'] = $info['brand_name'];
		$data['memory_name'] = $info['memory_name'];
		$data['attribute_name'] = $info['attribute_name'];
		$data['colour_name'] = $info['colour_name'];
		$data['marker'] = $info['marker'];
		$data['unit'] = $info['unit'];
		$data['selling_price'] = $info['selling_price'];
		$data['trade_price'] = $info['trade_price'];
		$data['profit_bonus'] = $info['profit_bonus'];
		$data['turnover_bonus'] = $info['turnover_bonus'];
		$data['bar_code'] = $info['bar_code'];
		$data['warning_number'] = $info['warning_number'];
		$data['warning_overdue'] = $info['warning_overdue'];
		$data['describes'] = $info['describes'];
		$data['addtime'] = time();
		if(!(new Goods())->updateGoods(['goods_id'=>$info['id']],$data))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 获取商品列表
	*/
	public static function getGoodsList($info,$cat = false)
	{
		$goodslist = (new Goods())->getGoodsList(self::is_where($info),10,$info['page']);
		if($cat === true)
        {
            $Category = new Category();
            foreach($goodslist['data'] as $i=>$vo)
            {
                $goodslist['data'][$i]['category_id'] = $Category->getCategoryField(['category_id'=>$vo['category_id']],'category_name');
                $goodslist['data'][$i]['cat_id'] = $Category->getCategoryField(['category_id'=>$vo['cat_id']],'category_name');
            }
        }
		return $goodslist;
	}
	/**
	* where 整理
	*/
	private function is_where($info)
	{
		$where['shop_id'] = Session::get('admin.shop_id');
        /*产品属性*/
		if($info['attribute_name'] != '' && $info['attribute_name'])
		{
			$where['attribute_name'] = $info['attribute_name'];
		}
        /*产品品牌*/
		if($info['brand_name'] != '' && $info['brand_name'])
		{
			$where['brand_name'] = $info['brand_name'];
		}
        /*产品子分类*/
		if($info['cat_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['cat_id'] = $info['cat_id'];
		}
        /*产品分类*/
		if($info['category_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['category_id'] = $info['category_id'];
		}
        /*产品颜色*/
		if($info['colour_name'] != '' && $info['colour_name'])
		{
			$where['colour_name'] = $info['colour_name'];
		}
        /*产品内存*/
		if($info['memory_name'] != '' && $info['memory_name'])
		{
			$where['memory_name'] = $info['memory_name'];
		}
        /*关键字搜索*/
		if($info['sreach'])
		{
			$where['goods_name|abbreviation|goods_sn'] = ['like','%'.$info['sreach'].'%'];
		}
        /*时间区间*/
        if($info['start'] != '' || $info['end'] != '')
		{
			if($info['start'])
			{
				$where['addtime'][] = ['>',strtotime($info['start'])];
			}
			if($info['end'])
			{
				$where['addtime'][] = ['<',strtotime($info['end'])];
			}
			return $where;
		}
        /*上月、当前月*/
        if(array_key_exists('shijian',$info))
        {
            if($info['shijian'] != '')
            {
                if($info['shijian'] == CommonModel::NUMBER_ZERO)
                {
                    $where['addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
                    $where['addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
                }else{
                    $where['addtime'][] = ['>',mktime(0, 0, 0,date('m')-1,1,date('Y'))];
                    $where['addtime'][] = ['<',mktime(0, 0, 0,date('m'),0,date('Y'))];
                }
            }
        }else{
            $where['addtime'][] = ['>',mktime(0,0,0,date('m'),1,date('Y'))];
            $where['addtime'][] = ['<',mktime(23,59,59,date('m'),date('t'),date('Y'))];
        }
        
		return $where;
	}
	/**
	* 删除
	*/
	public static function delGoods($id)
	{
		if((new Goods())->delGoods(['goods_id'=>$id]) === false)
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 商品信息
	* $ty 是否获取分类名称 true 获取
	*/
	public static function goodsInfo($id,$ty = false)
	{
		$goods = Goods::get($id)->toArray();
		if($ty === true)
		{
			$Category = new Category();
			$goods['category_id'] = $Category->getCategoryField(['category_id'=>$goods['category_id']],'category_name');
			$goods['cat_id'] = $Category->getCategoryField(['category_id'=>$goods['cat_id']],'category_name');
		}
		return $goods;
	}
    /**
    * 库存详情
    */
    public static function stockInfo($id,$ty = false)
    {
        $stock = Stock::get($id)->toArray();
        $shop = $stock['position']==1?'仓库':'店铺';
        $stock['position'] = "【{$shop}】{$stock['remarks']}";
        if($ty === true)
        {
            $stock['supplier_id'] = (new Supplier())->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
        }
        return $stock;
    }
	/**
	* 添加库存信息
	*/
	public static function setStock($info)
	{
		$data['goods_id'] = $info['id'];
		$data['imei'] = $info['imei'];
		$data['sn'] = $info['sn'];
		$data['number'] = $info['number'];
        $data['pur_number'] = $info['number'];
		$data['buying_price'] = $info['buying_price'];
		$data['supplier_id'] = $info['supplier_id'];
		$data['contract_sn'] = $info['contract_sn'];
		$data['period_time'] = strtotime($info['period_time']);
		$data['position'] = $info['position'];
		$data['remarks'] = $info['remarks'];
		$data['addtime'] = time();
		if(!(new Stock())->serStock($data))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 编辑
	*/
	public static function editStorage($info)
	{
		$data['imei'] = $info['imei'];
		$data['sn'] = $info['sn'];
		$data['number'] = $info['number'];
		$data['buying_price'] = $info['buying_price'];
		$data['supplier_id'] = $info['supplier_id'];
		$data['contract_sn'] = $info['contract_sn'];
		$data['period_time'] = strtotime($info['period_time']);
		$data['position'] = $info['position'];
		$data['remarks'] = $info['remarks'];
		if(!(new Stock())->updateStorage(['stock_id'=>$info['id']],$data))
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 商品库存信息
	*/
	public static function stockList($info)
	{
        $where['g.shop_id'] = Session::get('admin.shop_id');
		$where['s.state'] = CommonModel::NUMBER_ZERO;
        $where['s.period_time'] = ['>=',strtotime(date('Y-m-d',time()))];
		if($info['sreach'])
		{
			$where['s.contract_sn'] = ['like','%'.$info['sreach'].'%'];
		}
		
		$Supplier = new Supplier();
		$Stock = (new Stock())->getStockList($where,'g.goods_name,s.*',10,$info['page']);
		foreach($Stock['data'] as $i=>$v)
		{
			$Stock['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$v['supplier_id']],'supplier_name');
		}
		return $Stock;
	}
	/**
	* 删除
	*/
	public static function delStorage($id)
	{
		if((new Stock())->delStorage(['stock_id'=>$id]) === false)
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 库存报损
	*/
	public static function setStockloss($info)
	{
		$Stock = new Stock();
		$stockInfo = $Stock->getStockInfo(['stock_id'=>$info['id']]);
		if($stockInfo['number'] < $info['number'])
		{
			/*库存数量不足*/
			return back(config('state.STATUS_CODE_THREE'),'库存数量不足');
		}else if($stockInfo['number'] == $info['number'])
		{
			/*开启事物*/
			Db::startTrans();
			$stockInfo['fid'] = $stockInfo['stock_id'];
			$stockInfo['state'] = CommonModel::NUMBER_TWO;
			$stockInfo['number'] = $info['number'];
			$stockInfo['news_name'] = $info['news_name'];
			$stockInfo['position'] = $info['position'];
			$stockInfo['remarks'] = $info['remarks'];
			$stockInfo['addtime'] = time();
			unset($stockInfo['stock_id']);
			if(!$Stock->serStock($stockInfo))
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			/*修改当前状态*/
			if($Stock->updateStorage(['stock_id'=>$info['id']],['number'=>0,'is_show'=>1]) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			Db::commit();
			return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
		}else{
			/*新添加一条报损信息，并且减去库存*/
			$number = intval($stockInfo['number']) - intval($info['number']);
			/*开启事物*/
			Db::startTrans();
			$stockInfo['fid'] = $stockInfo['stock_id'];
			$stockInfo['state'] = CommonModel::NUMBER_TWO;
			$stockInfo['number'] = $info['number'];
			$stockInfo['news_name'] = $info['news_name'];
			$stockInfo['position'] = $info['position'];
			$stockInfo['remarks'] = $info['remarks'];
			$stockInfo['addtime'] = time();
			unset($stockInfo['stock_id']);
			if(!$Stock->serStock($stockInfo))
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			/*修改当前状态*/
			if($Stock->updateStorage(['stock_id'=>$info['id']],['number'=>$number]) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			Db::commit();
			return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
		}
	}
	/**
	* 库存信息
	*/
	public static function stockLossList($info,$where,$field,$cat = false)
	{
		$whereone = self::is_where($info);
        $wheretwo = [];
		if($whereone)
		{
			foreach($whereone as $key=>$value)
			{
				$wheretwo['g.' . $key] = $value;
			}
		}
        /*供应商*/
		if($info['supplier_id'] != CommonModel::NUMBER_ZERO)
		{
			$where['s.supplier_id'] = $info['supplier_id'];
		}
        /*状态*/
		if($info['state'] != CommonModel::NUMBER_ZERO)
		{
			$where['s.state'] = $info['state'];
		}
		$where = array_merge($where,$wheretwo);
        $where['s.is_show'] = 0;
        $where['s.headquarters'] = 0;
		$Stock = (new Stock())->getStockList($where,$field,10,$info['page']);
        if($cat === true)
        {
            $Category = new Category();
            $Supplier = new Supplier();
            foreach($Stock['data'] as $i=>$vo)
            {
                $Stock['data'][$i]['category_id'] = $Category->getCategoryField(['category_id'=>$vo['category_id']],'category_name');
                $Stock['data'][$i]['cat_id'] = $Category->getCategoryField(['category_id'=>$vo['cat_id']],'category_name');
                $Stock['data'][$i]['supplier_id'] = $Supplier->fieldSuppliers(['supplier_id'=>$vo['supplier_id']],'supplier_name');
                $shop = $vo['position']==1?'仓库':'店铺';
                $Stock['data'][$i]['position'] = "【{$shop}】{$vo['remarks']}";
                $Stock['data'][$i]['period_time'] = date('Y/m/d',$vo['period_time']);
            }
        }
		return $Stock;
	}
	/**
	* 恢复库存
	*/
	public function recoveryStock($info)
	{
		/*开启事物*/
		Db::startTrans();
		$Stock = new Stock();
		/*获取库存信息*/
		$stockList = $Stock->stockList(['s.stock_id'=>['in',$info['ids']],'g.shop_id'=>Session::get('admin.shop_id')],'stock_id,fid,number');
		foreach($stockList as $vo)
		{
			/*修改父级库存信息*/
			$data['state'] = CommonModel::NUMBER_ZERO;
			$data['number'] = ['inc',$vo['number']];
			if($Stock->updateStorage(['stock_id'=>$vo['fid']],$data) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
			/*关闭当前库存信息*/
			if($Stock->updateStorage(['stock_id'=>$vo['stock_id']],['is_show'=>1]) === false)
			{
				Db::rollback();
				return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
			}
		}
		
		Db::commit();
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
	/**
	* 返回总部
	*/
	public static function returnStock($info)
	{
		if((new Stock())->updateStorage(['stock_id'=>['in',$info['ids']]],['headquarters'=>1]) === false)
		{
			return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
		}
		return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
	}
    /**
    * 修改保质期
    */
    public static function editOverdue($info)
    {
        $Stock = new Stock();
        /*判断数量*/
        $number = $Stock->fieldStorage(['stock_id'=>$info['id']],'number');
        if($number < $info['number'])
        {
            return back(config('state.STATUS_CODE_SIX'),config('state.STATUS_MSG_SIX'));
        }
        if($number == $info['number']){
            /*全部商品直接修改*/
            if((new Stock())->updateStorage(['stock_id'=>$info['id']],['period_time'=>strtotime($info['period_time'])]) === false)
            {
                return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
            }
            return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
        }
        /*部分商品修改*/
        $stockInfo = $Stock->getStockInfo(['stock_id'=>$info['id']]);
        unset($stockInfo['stock_id']);
        $stockInfo['period_time'] = strtotime($info['period_time']);
        $stockInfo['number'] = $info['number'];
        $stockInfo['addtime'] = time();
        /*开启事物*/
		Db::startTrans();
        if(!$Stock->serStock($stockInfo))
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        /*修改当前库存*/
        $num = intval($number) - intval($info['number']);
        if($Stock->updateStorage(['stock_id'=>$info['id']],['number'=>$num]) === false)
        {
            Db::rollback();
            return back(config('state.STATUS_CODE_TWO'),config('state.STATUS_MSG_TWO'));
        }
        Db::commit();
        return back(config('state.STATUS_CODE_ONE'),config('state.STATUS_MSG_ONE'));
    }
    /**
    * 产品历史
    */
    public static function historyGoods($info)
    {
        $where1 = self::is_where($info);
        $list = (new Goods())->getGoodsList($where1,10,$info['page']);
        $OrderGoods = new OrderGoods();
        $Stock = new Stock();
        foreach($list['data'] as $i=>$vo)
        {
            $where['goods_id'] = $vo['goods_id'];
            $where['state'] = 0;
            /*入库数量*/
            $list['data'][$i]['ruku'] = $Stock->stockNumber($where);
            /*退货数量*/
            $where['state'] = 3;
            $list['data'][$i]['tuihuo'] = $Stock->stockNumber($where);
            /*召回数量*/
            $where['state'] = 4;
            $list['data'][$i]['zhaohui'] = $Stock->stockNumber($where);
            /*销售数量*/
            unset($where['state']);
            $where['is_show'] = 0;
            $list['data'][$i]['xiaoshou'] = $OrderGoods->orderGoodsNumber($where,'number');
            /*总营业额（元）*/
            $list['data'][$i]['yingyee'] = $OrderGoods->orderGoodsNumber($where,'goods_money');
            /*总成本（元）*/
            $list['data'][$i]['chengben'] = $OrderGoods->orderGoodsNumber($where,'cost_money');
            /*总盈利（元）*/
            $list['data'][$i]['yingli'] = $OrderGoods->orderGoodsNumber($where,'profit_money');
        }
        return $list;
    }
}
